<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理后台 - 校园二手交易平台</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        .header {
            background: #333;
            color: white;
            padding: 15px;
            text-align: center;
        }
        .nav-tabs {
            background: white;
            padding: 0;
            margin: 0;
            display: flex;
            border-bottom: 1px solid #ddd;
        }
        .nav-tab {
            padding: 15px 30px;
            cursor: pointer;
            border-bottom: 3px solid transparent;
            transition: all 0.3s;
        }
        .nav-tab.active {
            border-bottom-color: #667eea;
            background: #f8f9fa;
        }
        .tab-content {
            display: none;
            padding: 20px;
        }
        .tab-content.active {
            display: block;
        }
        .data-table {
            width: 100%;
            background: white;
            border-radius: 5px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .data-table table {
            width: 100%;
            border-collapse: collapse;
        }
        .data-table th {
            background: #f8f9fa;
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        .data-table td {
            padding: 15px;
            border-bottom: 1px solid #eee;
        }
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            margin-right: 5px;
            font-size: 12px;
        }
        .btn-success {
            background: #28a745;
            color: white;
        }
        .btn-danger {
            background: #dc3545;
            color: white;
        }
        .btn-warning {
            background: #ffc107;
            color: #212529;
        }
        .btn-primary {
            background: #007bff;
            color: white;
        }
        .status-badge {
            padding: 4px 8px;
            border-radius: 3px;
            font-size: 12px;
            font-weight: bold;
        }
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        .status-approved {
            background: #d4edda;
            color: #155724;
        }
        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }
        .logout-btn {
            position: absolute;
            top: 15px;
            right: 20px;
            background: #dc3545;
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.4);
        }
        .modal-content {
            background-color: #fefefe;
            margin: 10% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 40%;
            border-radius: 5px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
        }
        .modal-header {
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }
        .modal-header h3 {
            margin: 0;
        }
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }
        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }
        .modal-body {
            padding: 20px 0;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .form-group input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 3px;
            box-sizing: border-box;
        }
        .modal-footer {
            padding-top: 10px;
            border-top: 1px solid #eee;
            text-align: right;
        }
    </style>
</head>
<body>
<div class="header">
    <h2>管理后台</h2>
    <button class="logout-btn" onclick="logout()">退出登录</button>
</div>

<div class="nav-tabs">
    <div class="nav-tab active" onclick="showTab('users')">用户管理</div>
    <div class="nav-tab" onclick="showTab('items')">商品审核</div>
    <div class="nav-tab" onclick="showTab('all-items')">商品管理</div>
</div>

<div id="users-tab" class="tab-content active">
    <h3>用户管理</h3>
    <div class="data-table">
        <table>
            <thead>
            <tr>
                <th>用户ID</th>
                <th>学号</th>
                <th>昵称</th>
                <th>手机号</th>
                <th>注册时间</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="usersTable">
            <!-- 用户数据将通过JavaScript加载 -->
            </tbody>
        </table>
    </div>
</div>

<div id="items-tab" class="tab-content">
    <h3>商品审核</h3>
    <div class="data-table">
        <table>
            <thead>
            <tr>
                <th>商品ID</th>
                <th>标题</th>
                <th>分类</th>
                <th>价格</th>
                <th>卖家</th>
                <th>图片</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="itemsTable">
            <!-- 商品数据将通过JavaScript加载 -->
            </tbody>
        </table>
    </div>
</div>

<div id="all-items-tab" class="tab-content">
    <h3>商品管理</h3>
    <div class="data-table">
        <table>
            <thead>
            <tr>
                <th>商品ID</th>
                <th>标题</th>
                <th>分类</th>
                <th>价格</th>
                <th>卖家</th>
                <th>状态</th>
                <th>创建时间</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="allItemsTable">
            <!-- 所有商品数据将通过JavaScript加载 -->
            </tbody>
        </table>
    </div>
</div>

<!-- 用户编辑模态框 -->
<div id="editUserModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>编辑用户信息</h3>
            <span class="close" onclick="closeEditUserModal()">&times;</span>
        </div>
        <div class="modal-body">
            <form id="editUserForm">
                <input type="hidden" id="editUserId">
                <div class="form-group">
                    <label for="editStudentId">学号</label>
                    <input type="text" id="editStudentId" required>
                </div>
                <div class="form-group">
                    <label for="editNickname">昵称</label>
                    <input type="text" id="editNickname" required>
                </div>
                <div class="form-group">
                    <label for="editPhone">手机号</label>
                    <input type="tel" id="editPhone" required>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button class="btn btn-primary" onclick="saveUserChanges()">保存</button>
            <button class="btn btn-danger" onclick="closeEditUserModal()">取消</button>
        </div>
    </div>
</div>

<!-- 商品详情模态框 -->
<div id="itemDetailsModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <span class="close" onclick="closeItemDetailsModal()">&times;</span>
            <h3>商品详情</h3>
        </div>
        <div class="modal-body" id="itemDetailsModalBody">
            <!-- 商品详细信息将在此处加载 -->
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeItemDetailsModal()">关闭</button>
        </div>
    </div>
</div>

<script>
    let currentUser = null;

    // 检查管理员权限
    function checkAdminAuth() {
        const userData = localStorage.getItem('user');
        const token = localStorage.getItem('token'); // 获取 token

        if (!userData || !token) { // 同时检查 userData 和 token
            alert('未登录或会话已过期，请重新登录。');
            window.location.href = 'login.html';
            return;
        }
        currentUser = JSON.parse(userData);
        if (currentUser.userRole !== 'admin') {
            alert('权限不足');
            window.location.href = 'index.html';
            return;
        }
    }

    // 切换选项卡
    function showTab(tabName) {
        // 隐藏所有选项卡内容
        document.querySelectorAll('.tab-content').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelectorAll('.nav-tab').forEach(tab => {
            tab.classList.remove('active');
        });

        // 显示选中的选项卡
        document.getElementById(tabName + '-tab').classList.add('active');
        event.target.classList.add('active');

        // 加载相应数据
        if (tabName === 'users') {
            loadUsers();
        } else if (tabName === 'items') {
            loadPendingItems();
        } else if (tabName === 'all-items') {
            loadAllItems();
        }
    }

    // 加载用户列表
    async function loadUsers() {
        try {
            const token = localStorage.getItem('token');
            if (!token) {
                console.warn('Token not found. Cannot load users.');
                alert('未登录或会话已过期，请重新登录。');
                window.location.href = 'login.html';
                return;
            }

            const response = await fetch('/api/admin/users', {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const users = await response.json();

            const tbody = document.getElementById('usersTable');
            tbody.innerHTML = '';

            if (users.length === 0) {
                tbody.innerHTML = '<tr><td colspan="6" style="text-align: center;">暂无用户数据。</td></tr>';
                return;
            }

            users.forEach(user => {
                const row = document.createElement('tr');
                row.innerHTML = `
                        <td>${user.userId}</td>
                        <td>${user.studentId}</td>
                        <td>${user.nickname}</td>
                        <td>${user.phone}</td>
                        <td>${new Date(user.createdAt).toLocaleDateString()}</td>
                        <td>
                            <button class="btn btn-primary" onclick="openEditUserModal(${user.userId})">编辑</button>
                            <button class="btn btn-danger" onclick="deleteUser(${user.userId})">删除</button>
                        </td>
                    `;
                tbody.appendChild(row);
            });
        } catch (error) {
            console.error('加载用户失败:', error);
            alert('加载用户失败，请检查控制台。');
        }
    }

    // 加载待审核商品
    async function loadPendingItems() {
        const tbody = document.getElementById('itemsTable');
        tbody.innerHTML = '<tr><td colspan="7" style="text-align: center;">加载待审核商品...</td></tr>';
        try {
            const token = localStorage.getItem('token');
            const response = await fetch('/api/items/by-status?status=审核中', {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });
            if (!response.ok) {
                throw new Error('Failed to fetch pending items');
            }
            const items = await response.json();
            displayItemsTable(items);
        } catch (error) {
            console.error('加载待审核商品失败:', error);
            tbody.innerHTML = '<tr><td colspan="7" style="text-align: center;">加载失败。</td></tr>';
        }
    }

    // 加载所有商品
    async function loadAllItems() {
        const tbody = document.getElementById('allItemsTable');
        tbody.innerHTML = '<tr><td colspan="8" style="text-align: center;">加载所有商品...</td></tr>';
        try {
            const token = localStorage.getItem('token');
            const response = await fetch('/api/items', {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });
            if (!response.ok) {
                throw new Error('Failed to fetch all items');
            }
            const items = await response.json();
            displayAllItemsTable(items);
        } catch (error) {
            console.error('加载所有商品失败:', error);
            tbody.innerHTML = '<tr><td colspan="8" style="text-align: center;">加载失败。</td></tr>';
        }
    }

    // 打开编辑用户模态框
    async function openEditUserModal(userId) {
        try {
            const response = await fetch(`/api/admin/users/${userId}`);
            const user = await response.json();

            document.getElementById('editUserId').value = user.userId;
            document.getElementById('editStudentId').value = user.studentId;
            document.getElementById('editNickname').value = user.nickname;
            document.getElementById('editPhone').value = user.phone;

            document.getElementById('editUserModal').style.display = 'block';
        } catch (error) {
            console.error('获取用户信息失败:', error);
            alert('获取用户信息失败');
        }
    }

    // 关闭编辑用户模态框
    function closeEditUserModal() {
        document.getElementById('editUserModal').style.display = 'none';
    }

    // 保存用户修改
    async function saveUserChanges() {
        const userId = document.getElementById('editUserId').value;
        const studentId = document.getElementById('editStudentId').value;
        const nickname = document.getElementById('editNickname').value;
        const phone = document.getElementById('editPhone').value;

        try {
            const response = await fetch(`/api/admin/users/${userId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    studentId,
                    nickname,
                    phone
                })
            });

            if (response.ok) {
                alert('用户信息更新成功');
                closeEditUserModal();
                loadUsers();
            } else {
                alert('更新失败');
            }
        } catch (error) {
            console.error('更新用户信息失败:', error);
            alert('更新失败');
        }
    }

    // 删除用户
    async function deleteUser(userId) {
        if (confirm('确定要删除此用户吗？')) {
            try {
                const response = await fetch(`/api/admin/users/${userId}`, {
                    method: 'DELETE'
                });
                if (response.ok) {
                    alert('用户删除成功');
                    loadUsers();
                } else {
                    alert('删除失败');
                }
            } catch (error) {
                console.error('删除用户失败:', error);
                alert('删除失败');
            }
        }
    }

    // 函数：显示待审核商品列表
    function displayItemsTable(items) {
        const tbody = document.getElementById('itemsTable');
        tbody.innerHTML = ''; // 清空现有数据

        if (items.length === 0) {
            tbody.innerHTML = '<tr><td colspan="8" style="text-align: center;">暂无待审核商品。</td></tr>';
            return;
        }

        items.forEach(item => {
            const row = tbody.insertRow();
            row.insertCell().textContent = item.itemId;
            row.insertCell().textContent = item.title;
            row.insertCell().textContent = item.category;
            row.insertCell().textContent = `¥${item.price.toFixed(2)}`;
            row.insertCell().textContent = item.sellerNickname || item.sellerId; // 显示昵称或ID

            const imageCell = row.insertCell();
            if (item.base64Image) {
                const img = document.createElement('img');
                img.src = item.base64Image;
                img.style.width = '50px'; // Set appropriate size
                img.style.height = '50px';
                img.style.objectFit = 'cover';
                imageCell.appendChild(img);
            } else {
                imageCell.textContent = '无图';
            }

            const statusCell = row.insertCell();
            statusCell.className = `status-badge status-${getStatusClass(item.status)}`;
            statusCell.textContent = item.status;

            const actionCell = row.insertCell();
            const detailBtn = document.createElement('button');
            detailBtn.className = 'btn btn-info'; // 使用 info 类以便区分，如果没有则使用 primary
            detailBtn.textContent = '详情';
            detailBtn.onclick = () => showItemDetailsModal(item.itemId);
            actionCell.appendChild(detailBtn);

            const approveBtn = document.createElement('button');
            approveBtn.className = 'btn btn-success';
            approveBtn.textContent = '通过';
            approveBtn.onclick = () => updateItemStatus(item.itemId, '出售中');
            actionCell.appendChild(approveBtn);

            const rejectBtn = document.createElement('button');
            rejectBtn.className = 'btn btn-danger';
            rejectBtn.textContent = '驳回';
            rejectBtn.onclick = () => updateItemStatus(item.itemId, '已下架'); // 或者其他合适的驳回状态
            actionCell.appendChild(rejectBtn);
        });
    }

    // 函数：显示所有商品列表
    function displayAllItemsTable(items) {
        const tbody = document.getElementById('allItemsTable');
        tbody.innerHTML = ''; // 清空现有数据

        if (items.length === 0) {
            tbody.innerHTML = '<tr><td colspan="8" style="text-align: center;">暂无商品。</td></tr>';
            return;
        }

        items.forEach(item => {
            const row = tbody.insertRow();
            row.insertCell().textContent = item.itemId;
            row.insertCell().textContent = item.title;
            row.insertCell().textContent = item.category;
            row.insertCell().textContent = `¥${item.price.toFixed(2)}`;
            row.insertCell().textContent = item.sellerNickname || item.sellerId; // 显示昵称或ID
            const statusCell = row.insertCell();
            statusCell.className = `status-badge status-${getStatusClass(item.status)}`;
            statusCell.textContent = item.status;
            row.insertCell().textContent = new Date(item.createdAt).toLocaleString();

            const actionCell = row.insertCell();
            const detailBtn = document.createElement('button');
            detailBtn.className = 'btn btn-primary';
            detailBtn.textContent = '详情';
            detailBtn.onclick = () => showItemDetailsModal(item.itemId); // 调用新函数显示详情
            actionCell.appendChild(detailBtn);

            const deleteBtn = document.createElement('button');
            deleteBtn.className = 'btn btn-danger';
            deleteBtn.textContent = '删除';
            deleteBtn.onclick = () => deleteItem(item.itemId); // 调用删除商品函数
            actionCell.appendChild(deleteBtn);
        });
    }

    // 函数：获取状态对应的CSS类
    function getStatusClass(status) {
        switch (status) {
            case '审核中': return 'pending';
            case '出售中': return 'approved';
            case '已售出': return 'sold'; // 可以添加这个状态的样式
            case '已下架': return 'rejected';
            default: return '';
        }
    }

    // 函数：更新商品状态
    async function updateItemStatus(itemId, newStatus) {
        const token = localStorage.getItem('token');
        if (!token) {
            alert('未登录或会话已过期，请重新登录。');
            window.location.href = 'login.html';
            return;
        }

        let url;
        let method = 'PUT';

        if (newStatus === '出售中') {
            url = `/api/admin/items/${itemId}/approve`;
        } else if (newStatus === '已下架') {
            url = `/api/admin/items/${itemId}/reject`;
        } else {
            alert(`不支持的状态: ${newStatus}`);
            return;
        }

        try {
            const response = await fetch(url, {
                method: method,
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });

            if (response.ok) {
                alert(`商品 ${itemId} 状态更新为 ${newStatus} 成功！`);
                loadPendingItems(); // 刷新待审核列表
                loadAllItems();     // 刷新所有商品列表
            } else {
                const errorText = await response.text();
                alert(`更新失败: ${errorText}`);
                console.error('更新商品状态失败:', errorText);
            }
        } catch (error) {
            console.error('更新商品状态失败:', error);
            alert('更新商品状态失败，发生网络错误。');
        }
    }

    // 函数：删除商品
    async function deleteItem(itemId) {
        if (!confirm('确定要删除该商品吗？')) {
            return;
        }
        const token = localStorage.getItem('token');
        if (!token) {
            alert('未登录或会话已过期，请重新登录。');
            window.location.href = 'login.html';
            return;
        }

        try {
            const response = await fetch(`/api/admin/items/${itemId}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });

            if (response.ok) {
                alert(`商品 ${itemId} 删除成功！`);
                loadAllItems(); // 刷新所有商品列表
            } else {
                const errorText = await response.text();
                alert(`删除失败: ${errorText}`);
                console.error('删除商品失败:', errorText);
            }
        } catch (error) {
            console.error('删除商品失败:', error);
            alert('删除商品失败，发生网络错误。');
        }
    }

    // 模态框：显示商品详情
    async function showItemDetailsModal(itemId) {
        const modal = document.getElementById('itemDetailsModal');
        const modalBody = document.getElementById('itemDetailsModalBody');
        modalBody.innerHTML = '加载中...';
        modal.style.display = 'block';

        try {
            const response = await fetch(`/api/items/${itemId}`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const item = await response.json();

            modalBody.innerHTML = `
                <p><strong>商品ID:</strong> ${item.itemId}</p>
                <p><strong>标题:</strong> ${item.title}</p>
                <p><strong>描述:</strong> ${item.description || '无'}</p>
                <p><strong>价格:</strong> ¥${item.price.toFixed(2)}</p>
                <p><strong>分类:</strong> ${item.category}</p>
                <p><strong>卖家ID:</strong> ${item.sellerId}</p>
                <p><strong>卖家昵称:</strong> ${item.sellerNickname || '未知'}</p>
                <p><strong>状态:</strong> ${item.status}</p>
                <p><strong>浏览次数:</strong> ${item.viewCount}</p>
                <p><strong>点赞次数:</strong> ${item.likeCount}</p>
                <p><strong>创建时间:</strong> ${new Date(item.createdAt).toLocaleString()}</p>
                <p><strong>更新时间:</strong> ${new Date(item.updatedAt).toLocaleString()}</p>
                ${item.base64Image ? `<p><strong>图片:</strong><br><img src="${item.base64Image}" style="max-width: 100%; height: auto;"></p>` : '<p><strong>图片:</strong> 无</p>'}
            `;

        } catch (error) {
            console.error('加载商品详情失败:', error);
            modalBody.innerHTML = '<p>加载商品详情失败。</p>';
        }
    }

    // 模态框：关闭
    function closeItemDetailsModal() {
        document.getElementById('itemDetailsModal').style.display = 'none';
    }

    // 退出登录
    function logout() {
        localStorage.removeItem('user');
        localStorage.removeItem('token');
        window.location.href = 'login.html';
    }

    // 点击模态框外部关闭
    window.onclick = function(event) {
        const modal = document.getElementById('editUserModal');
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    }

    // 页面加载时执行
    window.addEventListener('load', function() {
        checkAdminAuth();
        loadUsers();
    });
</script>
</body>
</html>
